<template>
  <div class="user">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/" class="user-tou">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <!-- 添加用户按钮 -->
        <el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加角色</el-button
          >
        </el-form-item>
        <!-- 角色列表区域 -->
      </el-form>
      <el-table :data="data" border style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand" width="60">
          <template #default="{ row }">
            <el-row
              :class="['bdbottom', indext === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item, indext) in row.children"
              :key="item.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeroles(row, item.id)" closable>{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="['bdbottom', indext2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, indext2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      @close="removeroles(row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      @close="removeroles(row, item3.id)"
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="60"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>

        <el-table-column prop="mg_state" label="操作">
          <template #default="{ row }">
            <!-- //修改按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="dialogFormedit(row)"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="shan(row)"
              >删除</el-button
            >

            <el-button
              icon="el-icon-menu"
              size="mini"
              type="warning"
              @click="fenroles(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="quanVisible"
      width="50%"
      @close="qunqin"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="quanform"
        :props="quanProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defkeys"
        ref="treeref"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="quanVisible = false">取 消</el-button>
        <el-button type="primary" @click="allroles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框 -->

    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      @close="rolesClose"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="用户名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="用户描述"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="queroles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- //编辑用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogFormedit2"
      @close="rolesClose1"
    >
      <el-form :model="editfrom" :rules="rules" ref="showform">
        <el-form-item
          label="用户名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editfrom.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="用户描述"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input v-model="editfrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormedit2 = false">取 消</el-button>
        <el-button type="primary" @click="querolesedit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getroles,
  tianrole,
  editrole,
  tianroleeatid,
  getrolesshan,
  quanrolesshan,
  quanrolesfen,
  quanrolessou,
} from "@/api/roles";
export default {
  name: "LoginIndex",
  data() {
    return {
      //接收渲染列表数据
      data: [],
      //添加用户弹框添加隐藏
      dialogFormVisible: false,

      //添加用户表单数据
      form: {
        roleName: "",
        roleDesc: "",
      },
      formLabelWidth: "100px",
      //修改表单数据
      reviseroles: {},
      //修改校验
      rules: {
        roleName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入用户描述",
            trigger: "blur",
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      //控制用户添加对话弹框
      showVisible: false,

      //编辑用户信息对象
      editfrom: {},
      //编辑用户对话框展示
      dialogFormedit2: false,
      //控制分配权限对话框的显示隐藏
      quanVisible: false,
      //所有权限数据
      quanform: [],
      //树形控件属性绑定对象
      quanProps: {
        // 实现父子嵌套使用childen属性label表示看到的文本
        label: "authName",
        children: "children",
      },
      //默认选中节点id的数值
      defkeys: [],
      //当前即将分配权限的角色id
      roleId: "",
    };
  },
  created() {
    this.getdata();
  },
  methods: {
    // dialogFormedit3() {
    //   console.log(11);
    //   this.dialogFormedit3 != this.dialogFormedit3;
    // },
    //获取数据
    async getdata() {
      const res = await getroles();
      // console.log(res);
      this.data = res.data;
    },
    rolesClose() {
      this.$refs.form.resetFields();
    },

    //添加用户
    queroles() {
      this.$refs.form.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        const res = await tianrole(this.form);
        console.log(res);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
      });
      this.dialogFormVisible = false;
      this.getdata();
    },

    //编辑用户对话框显示
    async dialogFormedit(id) {
      console.log(11);
      this.dialogFormedit2 = true;
      const res = await editrole(id);
      console.log(res);
      this.editfrom = res.data;
    },
    //监听修改用户对话框关闭事件
    rolesClose1() {
      this.$refs.showform.resetFields();
    },

    //编辑用户对话框确定按钮
    async querolesedit() {
      this.$refs.showform.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        //发起修改用户信息数据请求
        const res = await tianroleeatid({
          id: this.editfrom.roleId,
          roleName: this.editfrom.roleName,
          roleDesc: this.editfrom.roleDesc,
        });
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败");
        }
        this.$message.success("更新用户信息成功");
        //关闭对话框
        (this.dialogFormedit2 = false),
          //刷新数据列表
          this.getdata();
      });
    },
    //删除用户Id
    async shan(id) {
      console.log(id.id);
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(res);
      if (res !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const shan = await getrolesshan(id.id);
      console.log(shan);
      if (shan.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.initdata();
    },
    //根据id删除权限  close触发传数据
    async removeroles(role, rightID) {
      //弹框提示用户是否删除
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res !== "confirm") {
        return this.$message.info("取消删除");
      }
      //发起删除请求
      // console.log(role.id);
      // console.log(rightID);
      const res1 = await quanrolesshan(role.id, rightID);
      console.log(res1);
      if (res1.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      //更新三级权限
      role.children = res.data;
      //分配权限
    },
    //分配权限的对话框
    async fenroles(role) {
      // console.log(role);
      this.roleId = role.id;
      //弹窗开关
      this.quanVisible = true;
      const res = await quanrolesfen();
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限失败");
      }
      //获取到的数据保存起来
      this.quanform = res.data;
      // console.log(this.quanform);
      //递归获取三级节点id
      console.log(this.defkeys);
      this.getquanroles(role, this.defkeys);
    },
    // 在点击分配权限按钮弹出对话框之前获取三级
    //通过递归形式，获取角色下所有三级权限的Id保存到defkey数组中 节点id

    getquanroles(node, arr) {
      //如果当前node节点不包含children属性则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getquanroles(item, arr));
    },
    //清空权限
    qunqin() {
      this.defkeys = [];
    },
    //点击为角色分配权限
    async allroles() {
      //  定义一个数组，拿来放全选和半选的id，拿tree的引用去调用getCheckedKeys若节点可被选择则返回目前被选中的节点的 key 所组成的数组和getHalfCheckedKeys返回目前半选中的节点所组成的数组	两个函数，将两个数组合并成了一个新数组
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys(),
      ];
      const str = keys.join(",");
      // console.log(str);//105,116,102,107,109,154,155,101,104
      // 发送数据请求
      const res = await quanrolessou(this.roleId, { rids: str });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message("分配权限失败！");
      }
      this.$message.success("分配权限成功");
      //刷新角色列表数据
      this.getdata();
      //关闭对话框
      this.quanVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.user-tou {
  margin-bottom: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
